package com.gk.study.controller;

import com.gk.study.common.APIResponse;
import com.gk.study.common.CourseStatus;
import com.gk.study.common.ResponeCode;
import com.gk.study.entity.Course;
import com.gk.study.entity.Order;
import com.gk.study.entity.TeacherWallet;
import com.gk.study.entity.Thing;
import com.gk.study.mapper.ThingMapper;
import com.gk.study.permission.Access;
import com.gk.study.permission.AccessLevel;
import com.gk.study.service.CourseService;
import com.gk.study.service.OrderService;
import com.gk.study.service.TeacherWalletService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    private final static Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    OrderService service;
    @Autowired
    private TeacherWalletService teacherWalletService;  // 注入钱包服务
    @Autowired
    CourseService courseService;
    @Autowired
    ThingMapper thingMapper;


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public APIResponse list(){
        List<Order> list =  service.getOrderList();

        return new APIResponse(ResponeCode.SUCCESS, "查询成功", list);
    }

    // 用户订单
    @RequestMapping(value = "/userOrderList", method = RequestMethod.GET)
    public APIResponse userOrderList(String userId, String status){
        List<Order> list =  service.getUserOrderList(userId, status);
        return new APIResponse(ResponeCode.SUCCESS, "查询成功", list);
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @Transactional
    public APIResponse create(Order order) throws IOException {
        service.createOrder(order);
        return new APIResponse(ResponeCode.SUCCESS, "创建成功", order);
    }

    @Access(level = AccessLevel.ADMIN)
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public APIResponse delete(String ids){
        System.out.println("ids===" + ids);
        // 批量删除
        String[] arr = ids.split(",");
        for (String id : arr) {
            service.deleteOrder(id);
        }
        return new APIResponse(ResponeCode.SUCCESS, "删除成功");
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @Transactional
    public APIResponse update(Order order) throws IOException {
        service.updateOrder(order);
        return new APIResponse(ResponeCode.SUCCESS, "更新成功");
    }

    @Access(level = AccessLevel.ADMIN)
    @RequestMapping(value = "/cancelOrder", method = RequestMethod.POST)
    @Transactional
    public APIResponse cancelOrder(Long id) throws IOException {
        Order order = new Order();
        order.setId(id);
        order.setStatus("7"); // 7=取消
        service.updateOrder(order);
        return new APIResponse(ResponeCode.SUCCESS, "取消成功");
    }

    @Access(level = AccessLevel.LOGIN)
    @RequestMapping(value = "/cancelUserOrder", method = RequestMethod.POST)
    @Transactional
    public APIResponse cancelUserOrder(Long id) throws IOException {
        Order order = new Order();
        order.setId(id);
        order.setStatus("7"); // 7=取消
        service.updateOrder(order);
        return new APIResponse(ResponeCode.SUCCESS, "取消成功");
    }


    @PostMapping("/pay")
    @Transactional
    public APIResponse payOrder(@RequestParam Long orderId) {
        Order order = service.getById(orderId);
        Thing thing = thingMapper.selectById(order.getThingId());
        if (order.getStatus().equals("1")) { // 假设 "1" 是待支付状态
            // 更新订单状态为已支付（如 "3"）
            order.setStatus("3");
            service.updateById(order);

            // 创建课程记录
            Course course = new Course();
            course.setOrderId(order.getId());
            course.setTeacherId(order.getThingId()); // 教师ID（关联b_thing.id）
            course.setStudentId(order.getUserId());  // 学生ID（关联b_user.id）
//            course.setTitle(order.getTitle());       // 课程标题（从订单中获取）
            course.setStatus(CourseStatus.PENDING);  // 初始状态为待确认
            course.setStartTime(LocalDateTime.now()); // 设置默认开始时间
            course.setEndTime(LocalDateTime.now().plusDays(order.getDays())); // 根据天数计算结束时间
            course.setTeacherName(order.getTeacherName());
            course.setTitle(order.getSubject()); // 课程标题（从订单中获取）
            course.setStartTime(order.getCourseStartTime()); // 使用订单中的课程开始时间;
            course.setCover(order.getCover());
            course.setMobile(thing.getMobile());

            courseService.save(course);

            return APIResponse.success("支付成功");
        } else {
            return APIResponse.error("订单状态无效");
        }
    }

    @PostMapping("/complete")
    public APIResponse completeOrder(Long orderId) {
        Order order = service.getById(orderId);
        if ("3".equals(order.getStatus())) {
            order.setStatus("4"); // 4=已完成
            service.updateById(order);

            // 记录到教师钱包
            TeacherWallet wallet = new TeacherWallet();
            wallet.setTeacherId(order.getThingId());
            wallet.setOrderId(order.getId());
            wallet.setAmount(order.getTotalAmount());
            wallet.setStatus("completed");
            teacherWalletService.save(wallet); // 需要创建 TeacherWalletService
        }
        return new APIResponse(ResponeCode.SUCCESS, "课程已完成");
    }
}
